var models = require('../db');
var express = require('express');
const jwt = require('jsonwebtoken');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../sql');

// 连接数据库
var conn = mysql.createConnection(models.mysql);

conn.connect();

// 登录接口
router.post('/login', (req, res) => {
  var sql = $sql.loginInfo.login;
  var params = req.body;
  conn.query(sql, [params.userId, params.passWord], function (err, result) {
    var data = JSON.parse(JSON.stringify(result))
    console.log(data);
    if (data.length === 0) {
      return res.send({
        status: 504,
        msg: "用户名或密码错误"
      })
    } else {
      let content = {
        userId: params.userId
      }
      let secretOrPrivateKey = "_jwt"; // 这是加密的key（密钥）
      let token = jwt.sign(content, secretOrPrivateKey, {
        expiresIn: 60 * 60 * 1 // 1小时过期
      });
      console.log(data[0].userName);
      return res.send({
        status: 200,
        msg: "登录成功",
        userId: params.userId,
        userName:data[0].userName,
        permissions:data[0].permissions,
        token: token
      })
    }
  })
});
module.exports = router;
